<template>
  <!-- <map id="myMap" show-location /> -->
  <div style="position: relative;">
    <map id="map" :markers="markers" :scale="scale" :polyline="viewPolyline" v-if="initCenter.longitude"
         :longitude="initCenter.longitude"
         :latitude="initCenter.latitude">
      <cover-view slot="callout" v-show="flag">
        <cover-view marker-id="2" class="calloutCommon start">
          <cover-view class="text">
            发
          </cover-view>
          <cover-view class="pos">{{ logisticsStore.info.startCity }}</cover-view>
        </cover-view>
        <cover-view marker-id="1" class="calloutCommon end">
          <cover-view class="text">
            收
          </cover-view>
          <cover-view class="pos">
            {{ logisticsStore.info.city }}
          </cover-view>
        </cover-view>
        <cover-view marker-id="3" class="doing">
          <cover-view>
            {{ logisticsStore.info.trajectorys.length ? logisticsStore.info.trajectorys[0].eventType : '待发货' }}
          </cover-view>
        </cover-view>
      </cover-view>
      <cover-view class="mapStep" v-show="flag">
        <cover-view class="mapStep_content">
          <cover-view class="mapStep_get">
            收
          </cover-view>
          <cover-view class="mapStep_text">
            承运单号：
          </cover-view>
          <cover-view class="mapStep_billNo">
            {{ logisticsStore.info.billNo }}
          </cover-view>
          <image style="height: 88rpx; margin-left: auto;" mode="heightFix"
                 src="../../assets/images/orderTracking/bgCar.png">
          </image>
        </cover-view>
        <cover-view class="mapStep_startEnd">
          <nut-steps direction="vertical" progress-dot>
            <nut-step title="始发地">
              <template #content>
                <cover-view class="start_end_text">
                  <text>{{ logisticsStore.info.startProvince }}</text>
                  <text>{{ logisticsStore.info.startCity }}</text>
                </cover-view>
              </template>
              <template #icon>
                <view style="width:16rpx;height:16rpx;border:4rpx solid #0966ff;border-radius:50%;"></view>
              </template>
            </nut-step>
            <nut-step title="目的地" content="您的订单正在配送途中">
              <template #content>
                <cover-view class="start_end_text">
                  <text>{{ logisticsStore.info.province }}</text>
                  <text>{{ logisticsStore.info.city }}</text>
                </cover-view>
              </template>
              <template #icon>
                <view style="width:16rpx;height:16rpx;border:4rpx solid #08bf60;border-radius:50%;"></view>
              </template>

            </nut-step>
          </nut-steps>
        </cover-view>
        <view style="max-height: 300rpx;overflow-x: hidden; overflow-y: scroll;">
          <view class="mapStep_state">
            <nut-steps direction="vertical" progress-dot>
              <nut-step v-for="(t, i) in logisticsStore.info.trajectorys" :key="t.ssotId" title="已完成" content="您的订单已经打包完成，商品已发出">
                <template #title>
                  <cover-view>
                    {{ t.eventType }}
                  </cover-view>
                </template>
                <template #content>
                  <cover-view>
                    {{ timeFilter(t.creaTetime) }}
                  </cover-view>
                </template>
                <template #icon>
                  <image v-if="i == 0" style="width: 48rpx; height: 48rpx;"
                         src="../../assets/images/orderTracking/待发货.png"></image>
                  <image v-else-if="i == logisticsStore.info.trajectorys.length - 1" style="width: 48rpx; height: 48rpx;"
                         src="../../assets/images/orderTracking/first.png"></image>
                  <image v-else style="width: 16rpx; height: 16rpx;" src="../../assets/images/orderTracking/middle.png">
                  </image>
                </template>
              </nut-step>
            </nut-steps>
          </view>
        </view>
        <view class="mapStep_btn">
          <nut-button block color="#0966FF" type="primary" @click="toOrderDetail">运单详情</nut-button>
        </view>

      </cover-view>
    </map>
  </div>
</template>

<script lang="ts"  setup>
import Taro from "@tarojs/taro";
import { useDidShow } from "@tarojs/taro";
import { ref, reactive } from "vue";
import useMyOrderStore from "@/store/myOrder";
import { getLogisticsInfo } from "@/@api/orderTracking";
import { $get, $post } from "@/@api";
import logisticsInfoStore from "@/store/logistics";
const logisticsStore = logisticsInfoStore();
const order = useMyOrderStore()
let MapContext: any
const scale = ref()
const viewPolyline = ref<any>({})
const initCenter = ref({
  latitude: logisticsStore.info.slat,
  longitude: logisticsStore.info.sLng,
})

var markers = ref<any>([])
const flag = ref(false)
const stepHeight = ref('auto')

const getAddressByLngLat = async (lng,lat) => {
  const res:any = await $get('/selfmachine-system/addressBook/reverseGeocoding',{longitude:lng,latitude:lat})
  return res.data.data
}

useDidShow(async () => {
  // 获取订单详情
  // let orderRes:any = await $post(
  //     "/selfmachine-system/order/list",
  //     {
  //       billNo: logisticsStore.info.billNo
  //     }
  // )
  // order.orderList = orderRes.data.rows[0]

  let _this = this;
  MapContext = Taro.createMapContext("map", _this);

  stepHeight.value = logisticsStore.info.trajectorys.length * 140 + 'rpx'
  markers.value = [
    {
      iconPath: require("../../assets/images/orderTracking/end.png"),
      id: 1,
      latitude: logisticsStore.info.eLat,
      longitude: logisticsStore.info.eLng,
      width: 20,
      height: 20,

      customCallout: {
        display: 'ALWAYS',
        anchorX: 60,
        anchorY: 30

      },
    },

    {
      iconPath: require("../../assets/images/orderTracking/start.png"),
      id: 2,
      latitude: logisticsStore.info.sLat,
      longitude: logisticsStore.info.sLng,
      width: 20,
      height: 20,

      customCallout: {
        display: 'ALWAYS',
        anchorX: 60,
        anchorY: 30
      },
    },
    {
      iconPath: require("../../assets/images/orderTracking/xiaoche.png"),
      id: 3,
      latitude: logisticsStore.info.trajectorys.length ? logisticsStore.info.trajectorys[0].lat : logisticsStore.info.sLat,
      longitude: logisticsStore.info.trajectorys.length ? logisticsStore.info.trajectorys[0].lng : logisticsStore.info.sLng,
      width: 15,
      height: 30,
      customCallout: {
        display: 'ALWAYS',
        anchorX: 0,
        anchorY: 0
      },
      rotate: getRotate({
        latitude: logisticsStore.info.trajectorys.length ? logisticsStore.info.trajectorys[0].lat : logisticsStore.info.sLat,
        longitude: logisticsStore.info.trajectorys.length ? logisticsStore.info.trajectorys[0].lng : logisticsStore.info.sLng,
      },{
        latitude: logisticsStore.info.eLat,
        longitude: logisticsStore.info.eLng,
      })
    }
  ]

  let polyline:any = [{
    points: [{
      longitude: '',
      latitude: ''
    }, {
      longitude: '',
      latitude: ''
    }],
    color: "#29C74C",
    width: 5,
  }]
  const startAddress = await getAddressByLngLat(logisticsStore.info.sLng,logisticsStore.info.sLat)
  const endAddress = await getAddressByLngLat(logisticsStore.info.eLng,logisticsStore.info.eLat)
  const res:any = await $get('/selfmachine-system/branch/navigationRoute', {
    source: startAddress,
    destination: endAddress,
  })
  if(res.data.data.route && res.data.data.route.paths.length){
    let _path = res.data.data.route.paths[0]
    polyline[0].points = _path.steps.map((item)=>{
      return {
        longitude: item.polyline.split(';')[0].split(',')[0],
        latitude: item.polyline.split(';')[0].split(',')[1],
      }
    })
  }


  // polyline[0].points = [
  //   {
  //     longitude: logisticsStore.info.sLat,
  //     latitude: logisticsStore.info.sLng
  //   },
  // ]
  // logisticsStore.info.trajectorys.forEach((item)=>{
  //   polyline[0].points.push({
  //     latitude: item.lng,
  //     longitude: item.lat,
  //   })
  // })
  // polyline[0].points.push({
  //   longitude: logisticsStore.info.eLat,
  //   latitude: logisticsStore.info.eLng
  // })

  viewPolyline.value = polyline

  MapContext.includePoints({
    points: [
      { longitude: logisticsStore.info.sLng, latitude: logisticsStore.info.sLat },
      { longitude: logisticsStore.info.eLng, latitude: logisticsStore.info.eLat },
    ],
    padding: [100, 100, 100, 100],
    success() {
      setTimeout(() => {
        MapContext.setCenterOffset({
          offset: [0.5, 0.75],
        })
        scale.value = 6
        flag.value = true
      }, 500)
    }

  })



});

//运单详情
const toOrderDetail = async ()=>{
  let res: any = await $post(
      "/selfmachine-system/order/list",
      {
        billNo: logisticsStore.info.billNo,
      }
  )
  order.orderList = res.data.rows[0]
  Taro.redirectTo({
    url: "/pages/myOrder/order",
  })
}


//时间过滤
const timeFilter = (t) => {
  return times(t);
}
//时间过滤
function times(time) {
  var date = new Date(time);
  var Y = date.getFullYear() + "-";
  var M =
      (date.getMonth() + 1 < 10
          ? "0" + (date.getMonth() + 1)
          : date.getMonth() + 1) + "-";
  var D = date.getDate() + " ";
  var h = date.getHours() + ":";
  var m = date.getMinutes();
  var s = date.getSeconds();
  // console.log(Y+M+D+h+m+s);
  // return Y + M + D + h + m + s;

  return Y + M + D + h + m;
}

const getRotate = (po1, po2) => {
  if (!(po1 && po2)) return 0
  const lng_a = po1.longitude
  const lat_a = po1.latitude
  const lng_b = po2.longitude
  const lat_b = po2.latitude
  const a = ((90 - lat_b) * Math.PI) / 180
  const b = ((90 - lat_a) * Math.PI) / 180
  const AOC_BOC = ((lng_b - lng_a) * Math.PI) / 180
  const cosc = Math.cos(a) * Math.cos(b) + Math.sin(a) * Math.sin(b) * Math.cos(AOC_BOC)
  const sinc = Math.sqrt(1 - cosc * cosc)
  const sinA = (Math.sin(a) * Math.sin(AOC_BOC)) / sinc
  const A = (Math.asin(sinA) * 180) / Math.PI
  let rotate = 0
  if (lng_b > lng_a && lat_b > lat_a) rotate = A
  else if (lng_b > lng_a && lat_b < lat_a) rotate = 180 - A
  else if (lng_b < lng_a && lat_b < lat_a) rotate = 180 - A
  else if (lng_b < lng_a && lat_b > lat_a) rotate = 360 + A
  else if (lng_b > lng_a && lat_b == lat_a) rotate = 90
  else if (lng_b < lng_a && lat_b == lat_a) rotate = 270
  else if (lng_b == lng_a && lat_b > lat_a) rotate = 0
  else if (lng_b == lng_a && lat_b < lat_a) rotate = 180

  if (rotate > 360) {
    rotate = rotate - 360
  }
  return rotate
}



</script>



<style lang="scss">
#map {
  width: 100vw;
  height: 100vh;

  .calloutCommon {
    display: flex;

    .text {
      color: #fff;
      padding: 16rpx;
      border-radius: 10rpx 0 0 10rpx;
    }

    .pos {
      padding: 16rpx;
      border-radius: 0 10rpx 10rpx 0;
      background-color: #fff;
    }

  }

  .doing {
    background: rgba(0, 0, 0, 0.8);
    padding: 20px 40px;
    color: #fff;
    border-radius: 10px;

  }

  .start {

    .text {
      background-color: #FF8A00;
    }

    .pos {
      color: #FF8A00;
    }
  }

  .end {
    .text {
      background-color: #0966FF;
    }

    .pos {
      color: #0966FF;
    }
  }

  .mapStep {
    position: absolute;
    bottom: 0;
    width: 100%;
    left: 50%;
    transform: translateX(-50%);



    .mapStep_content {
      height: 62rpx;
      display: flex;
      padding: 10rpx;
      border-radius: 8px 8px 0px 0px;
      width: 95%;
      align-items: center;
      margin: auto;

      background: linear-gradient(96deg, #CCE0FF 0%, #FFFFFF 100%);
      // background-image: url('');

      .mapStep_get {
        font-size: 18rpx;
        color: #fff;
        background-color: #0EC365;
        padding: 6.5px;
        border-radius: 5px;
        margin-right: 20px;
      }

      .mapStep_text {
        font-size: 24rpx;
        margin-right: 20px;
      }

      .mapStep_billNo {
        font-size: 24rpx;
      }
    }

    .mapStep_startEnd {
      background-color: #fff;
      padding: 10rpx;
      height: 210rpx;
      border-radius: 0 0 16rpx 16rpx;
      width: 95%;
      margin: 0 auto 10px;



      --nut-steps-wait-icon-bg-color: #fff;


      .nut-steps-vertical.nut-steps-dot .nut-step-icon {
        width: 24rpx;
        height: 24rpx;
      }

      .start_end_text {
        font-weight: bold;
        font-size: 32rpx;
        color:#252525;
        text {
          margin-right: 16rpx;
        }
      }
    }

    .mapStep_state {
      width: 100%;
      background-color: #fff;
      height: v-bind(stepHeight);
      padding: 10rpx;
      // overflow-y: auto;

      .nut-steps-vertical.nut-steps-dot .nut-step-icon {
        width: 48rpx;
        height: 48rpx;
      }

      --nut-steps-wait-icon-bg-color: #fff;

    }

    .mapStep_btn {
      background-color: #fff;
      padding: 20px;
    }
  }
}
</style>
